/*
参数说明：
alertShow-弹出框参数{
  showmsg-服务器弹窗提示
  msg-服务器提示内容
  show-抽奖结果弹窗提示
}
userData-基本信息{
  point-用户积分
  signDays-签到总天数
  dayDate-今日信息展示用
}
components-商品组件信息{
  checklist-积分兑换商品List数组
  isMoney-是否显示金钱占位
  isScore-是否显示积分占位
  isRemove-是否显示购买按钮占位
  divsize-组件一排显示几个数据
  biaoqian-跳转积分详情还是商品详情界面(1 积分兑换界面  2 商品详情界面)
}
detail-签到记录数组
  日历组件参数可参考vuxAPI{
    show: true,
    value: '',
    range: false,
    replaceTextList: {'TODAY': '今'},
    weeksList: ['日', '一', '二', '三', '四', '五', '六 '],
    buildSlotFn: () => ''
  }

方法：
getList-获取日历的基础信息
qiandao-绘制已签记录信息
dayFn-根据今天的信息做数据格式转换处理好和服务器传回数据做比较
onShow-弹窗框弹出时触发的方法
onHide-弹窗框关闭时触发的方法
*/
<template>
  <div style="overflow-x:hidden">
    <img src="../../../assets/images/activities/qd_banner.png" style="width: 100%;height: 200px;"/>
    <alert v-model="alertshow.showmsg" :title="'提示'" @on-show="onShow" @on-hide="onHide">{{alertshow.msg}}</alert>
    <flexbox  wrap="alertshow.nowrap" :gutter="0"  style="padding-left: 20px;">
      <flexbox-item :span="3">
        <div class="flex-demo" style="padding-top: 25px;padding-bottom: 25px">
          <img :src="userData.userImg" id="userImg"/>
        </div>
      </flexbox-item>
      <flexbox-item :span="9">
      <!--<flexbox-item :span="4.5">-->
        <div class="flex-demo" style="padding-left: 5px;">
          <flexbox :gutter="-3" orient="vertical">
            <flexbox-item><p class="flex-demo" style="font-size: 16px;color: #333333">{{userData.username}}</p></flexbox-item>
            <flexbox-item>
              <p class="flex-demo" style="font-size: 13px;color:#dfdfdf;display: inline-block">连续签到</p>
              <p class="flex-demo" style="font-size: 13px;color:#dc7d7d;display: inline-block">{{userData.signDays}}</p>
              <p class="flex-demo" style="font-size: 13px;color:#dfdfdf;display: inline-block">天</p>
            </flexbox-item>
            <flexbox-item>
              <p class="flex-demo" style="font-size: 13px;color:#dfdfdf;display: inline-block">账户剩余</p>
              <p class="flex-demo" style="font-size: 13px;color:#dc7d7d;display: inline-block">{{userData.point}}</p>
              <p class="flex-demo" style="font-size: 13px;color:#dfdfdf;display: inline-block">积分</p>
            </flexbox-item>
          </flexbox>
        </div>
      </flexbox-item>
      <!--<flexbox-item :span="3.5">-->
        <!--<div>-->
          <!--<x-button  style="background-color: #0b97c4;color: #ffffff"  @click.native="moneyFn" disabled type="primary">提现</x-button>-->
        <!--</div>-->
      <!--</flexbox-item>-->
    </flexbox>
    <div style="font-size: 20px;text-align: center;color: #333333">{{userData.dayDate}}</div>
    <div class="calendar">
      <inline-calendar
        class="inline-calendar-demo"
        :show.sync="show"
        v-model="value"
        :range="range"
        :hide-header="true"
        :hide-week-list="false"
        :replace-text-list="replaceTextList"
        :weeks-list="weeksList"
        :render-function="buildSlotFn">
      </inline-calendar>
    </div>
    <div style="padding: 18px 10px 55px 10px;">
      <divider style="color: #333333">签到活动规则</divider>
      <p style="font-size: 12px;color: #aaa9a9">1.签到第1天，获得1积分奖励</p>
      <p style="font-size: 12px;color: #aaa9a9">2.连续签到第2天，获得2积分奖励</p>
      <p style="font-size: 12px;color: #aaa9a9">3.连续签到3天及以上，每天可获得3积分奖励</p>
      <p style="font-size: 12px;color: #aaa9a9">4.连续签到每满5天，均可随机获得1-5积分的奖励</p>
      <p style="font-size: 12px;color: #aaa9a9">5.连续签到每满30天，均可随机获得10-30积分的奖励</p>
      <p style="font-size: 12px;color: #aaa9a9">6.断签则恢复到第1天，连续签到奖励从第1天开始计算</p>
      <p style="font-size: 12px;color: #aaa9a9">7.每天仅可签到一次</p>
      <p style="font-size: 12px;color: #aaa9a9">备注：积分及使用规则请前往我的积分查看</p>
    </div>
    <!--<div style="padding: 15px">-->
    <!--<x-button @click.native="scoreShopfn" type="primary">立即签到</x-button>-->
    <!--</div>-->
    <group :title="''">
      <div style="background-color: #f1f7ff;height: 40px;"><p style="padding-top: 10px;padding-left: 5px">兑换商品</p></div>
      <shopGood :isList="components.checklist" :isMoney="components.isMoney" :isScore="components.isScore" :isRemove="components.isRemove " :divsize="components.size" :biaoqian="components.biaoqian"></shopGood>
    </group>
    <!--<group>-->
    <!--<cell title="current value" :value="value"></cell>-->
    <!--</group>-->
  </div>
</template>
<script>
  import { Flexbox, FlexboxItem, XButton, Group, Cell, InlineCalendar, Alert, Divider } from 'vux'
  import shopGood from '../../../components/shopCommodity/shopGoods_Q.vue'
  import * as urls from '../../../api/urls'
  import * as types from '../../../store/types'
  import $ from 'jquery'
  //  import api from '../../../assets/api/index'

  export default {
    components: {
      Flexbox,
      FlexboxItem,
      XButton,
      Group,
      InlineCalendar,
      Cell,
      shopGood,
      Alert,
      Divider
    },
    mounted: function () {
      this.setShopCarNum()
      if (this.$store.state.userInfo.id === '' || this.$store.state.userInfo.id === null || this.$store.state.userInfo.id === undefined) {
        this.userId = this.getQueryString('userId')
        if (this.userId !== '' && this.userId !== null && this.userId !== undefined) {
          this.$store.commit(types.USER_INFO, {id: this.userId})
          this.getList()
          this.getPointList()
          this.qiandao()
          this.dayFn()
        } else {
          let url = window.location.origin
          window.location.href = url + '/api/wxAuth/index?type=t2'
        }
      } else {
        this.userId = this.$store.state.userInfo.id
        this.getList()
        this.getPointList()
        this.qiandao()
        this.dayFn()
        let that = this
        this.http(urls.activitiesSign, {userId: this.userId}, function (res) {
          if (res.status === 100) {
            that.detail.push(that.dayNum)
            that.getList()
            that.qiandao()
            that.setShopCarNum()
            that.alertshow.showmsg = true
            that.alertshow.msg = '签到成功~'
          } else {
            if (res.data.hasSign === true) {
              that.alertshow.showmsg = false
            } else {
              that.alertshow.showmsg = true
              that.alertshow.msg = res.errMsg
            }
          }
        }, function (res) {
          that.alertshow.showmsg = true
          that.alertshow.msg = res
        })
      }
      $(document).ready(function () {
        let classnextArry = document.getElementsByClassName('vux-next-icon')
        let classprevArry = document.getElementsByClassName('vux-prev-icon')
        document.getElementsByClassName('is-today')[0].style.color = '#3d82e5'
        for (let i = 0; i < classnextArry.length; i++) {
          classnextArry[i].style.borderColor = '#3d82e5'
        }
        for (let i = 0; i < classprevArry.length; i++) {
          classprevArry[i].style.borderColor = '#3d82e5'
        }
      })
      $(function () {
        $('.inline-calendar').on('click', 'td', function () {
          $('.inline-calendar td > span')[0].setAttribute('style', 'background-color: #fff !important')
        })
      })
      this.weixinfn41()
    },
    data () {
      return {
        userId: '',
        detail: [],
        dayNum: '',
        alertshow: {
          showmsg: false,
          msg: ''
        },
        userData: {
          point: '',
          signDays: '',
          dayDate: '',
          username: '',
          userImg: ''
        },
        components: {
          checklist: [],
          isMoney: false,
          isRemove: false,
          isScore: true,
          size: 6,
          biaoqian: 1
        },
        show: true,
        value: '',
        range: false,
        replaceTextList: {'TODAY': '今'},
        weeksList: ['日', '一', '二', '三', '四', '五', '六 '],
        buildSlotFn: () => ''
      }
    },
    watch: {
      // 根据监测数据变化方法实现点击今日日期签到功能
      value (val) {
        // 点击签到 （功能暂时屏蔽，设计需求改为进入界面即签到）
//        if (this.dayNum === val) {
//          let userId = this.$store.state.userInfo.id
//          let that = this
//          this.http(urls.activitiesSign, {userId: userId}, function (res) {
//            if (res.status === 100) {
//              that.detail.push(that.dayNum)
//            } else {
//              that.alertshow.showmsg = true
//              that.alertshow.msg = res.errMsg
//            }
//          }, function (res) {
//            that.alertshow.showmsg = true
//            that.alertshow.msg = res
//          })
//        }
      }
    },
    methods: {
      setShopCarNum () {
        let userId = this.$store.state.userInfo.id
        let that = this
        that.http(urls.cartAndSign, {userId: userId}, function (res) {
          if (res.status === 100) {
            if (res.data.hasSign === true) {
              that.$root.$children[0].$data.hasSign = false
            } else {
              that.$root.$children[0].$data.hasSign = true
            }
          } else {
            that.alertShow.showmsg = true
            that.alertShow.msg = res.errMsg
          }
        }, function (res) {
          that.alertShow.showmsg = true
          that.alertShow.msg = res
        })
      },
      weixinfn41 () {
        let that = this
        let userId = this.$store.state.userInfo.id
        let logo = this.$store.state.empower.LOGO
        let url = window.location.origin
        let link = url + '/api/wxAuth/index?type=t1' + '&uid=' + userId
        that.$wechat.onMenuShareAppMessage({
          title: '孝行通', // 分享标题
          desc: '孝行通·微商城 一个让子女为父母尽孝的老年服务平台', // 分享描述
          link: link, // 分享链接
          imgUrl: logo, // 分享图标
          success: function () {
            // 用户确认分享后执行的回调函数
          },
          cancel: function () {
            // 用户取消分享后执行的回调函数
          }
        })
        that.$wechat.onMenuShareTimeline({
          title: '孝行通', // 分享标题
          link: link, // 分享链接
          imgUrl: logo, // 分享图标
          success: function () {
            // 用户确认分享后执行的回调函数
          },
          cancel: function () {
            // 用户取消分享后执行的回调函数
          }
        })
      },
      getQueryString (name) {
//        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
//        var r = window.location.search.substr(1).match(reg)
        let userId = window.location.href.substr('userId='.length + window.location.href.indexOf('?') + 1, window.location.href.length)
        return userId
//        if (r !== null) {
//          return (r[2])
//        } else {
//          return null
//        }
      },
      getList () {
        let userId = this.$store.state.userInfo.id
        let that = this
        this.http(urls.activitiesDetail, {userId: userId}, function (res) {
          if (res.status === 100) {
            if (res.data !== undefined) {
              if (res.data.detail !== null) {
                // 没有签到记录的时候数组为null
                that.detail = res.data.detail
              }
              that.userData.username = res.returnValue.nick
              that.userData.userImg = res.returnValue.avatar
              that.userData.signDays = res.data.signDays
              that.userData.point = res.data.point
            }
          } else {
            that.alertshow.showmsg = true
            that.alertshow.msg = res.errMsg
          }
        }, function (res) {
          that.alertshow.showmsg = true
          that.alertshow.msg = res.res
        })
      },
      getPointList () {
        let that = this
        this.http(urls.pointItem, {}, function (res) {
          if (res.status === 100) {
            if (res.data.page !== undefined) {
              if (res.data.page.list.length !== 0) {
                // 积分商品List
                that.components.checklist = []
                for (let i = 0; i < res.data.page.list.length; i++) {
                  let itemObj = {}
                  itemObj.url = res.data.page.list[i].imgUrl
                  itemObj.name = res.data.page.list[i].name
                  itemObj.itemId = res.data.page.list[i].itemId
                  itemObj.pointPrice = res.data.page.list[i].pointPrice
                  that.components.checklist.push(itemObj)
                }
              }
            }
          } else {
            that.alertshow.showmsg = true
            that.alertshow.msg = res.errMsg
          }
        }, function (res) {
          that.alertshow.showmsg = true
          that.alertshow.msg = res.res
        })
      },
      qiandao () {
        // 根据List绘制初始化日历签到
        let val = true
        let that = this
        this.buildSlotFn = val ? (line, index, data) => {
          let divStr = ''
          // 修改数据结构和服务器月份匹配 1-9月份前面加0
          if (parseInt(data.month_str) < 10) {
            data.month_str = '0' + parseInt(data.month_str)
          }
          console.log('this.dayNum', that.dayNum)
          // 根据List和组件内日历比对 达到签到效果
          for (let i = 0; i < that.detail.length; i++) {
            if (parseInt(data.day) < 10) {
              if (that.detail[i] === (data.year + '-' + data.month_str + '-0' + data.day)) {
                divStr += '<div style="position:absolute;z-index: 99;font-size:12px;text-align:center;top: 50%;left: 50%;-webkit-transform: translate(-50%, -50%);-moz-transform: translate(-50%, -50%);-ms-transform: translate(-50%, -50%);-o-transform: translate(-50%, -50%);transform: translate(-50%, -50%);"><h4 style="color: #3d82e5;border: 1px solid;border-radius: 20px;width: 22px;height: 22px;"></h4></div>'
//                if (that.dayNum === (data.year + '-' + data.month_str + '-0' + data.day)) {
//                  divStr += '<div style="position:absolute;z-index: 99;font-size:12px;text-align:center;top: 50%;left: 50%;-webkit-transform: translate(-50%, -50%);-moz-transform: translate(-50%, -50%);-ms-transform: translate(-50%, -50%);-o-transform: translate(-50%, -50%);transform: translate(-50%, -50%);"><h4 style="background-color: #3d82e5;color: #ffffff;border: 1px solid;border-radius: 20px;width: 22px;height: 22px;"></h4></div>'
//                } else {
//                  divStr += '<div style="position:absolute;z-index: 99;font-size:12px;text-align:center;top: 50%;left: 50%;-webkit-transform: translate(-50%, -50%);-moz-transform: translate(-50%, -50%);-ms-transform: translate(-50%, -50%);-o-transform: translate(-50%, -50%);transform: translate(-50%, -50%);"><h4 style="color: #3d82e5;border: 1px solid;border-radius: 20px;width: 22px;height: 22px;"></h4></div>'
//                }
              }
            } else {
              if (that.detail[i] === (data.year + '-' + data.month_str + '-' + data.day)) {
                divStr += '<div style="position:absolute;z-index: 99;font-size:12px;text-align:center;top: 50%;left: 50%;-webkit-transform: translate(-50%, -50%);-moz-transform: translate(-50%, -50%);-ms-transform: translate(-50%, -50%);-o-transform: translate(-50%, -50%);transform: translate(-50%, -50%);"><h4 style="color: #3d82e5;border: 1px solid;border-radius: 20px;width: 22px;height: 22px;"></h4></div>'
//                if (that.dayNum === (data.year + '-' + data.month_str + '-' + data.day)) {
//                  divStr += '<div style="position:absolute;z-index: -1;font-size:12px;text-align:center;top: 50%;left: 50%;-webkit-transform: translate(-50%, -50%);-moz-transform: translate(-50%, -50%);-ms-transform: translate(-50%, -50%);-o-transform: translate(-50%, -50%);transform: translate(-50%, -50%);"><h4 style="background-color: #3d82e5;color: #ffffff;border: 1px solid;border-radius: 20px;width: 22px;height: 22px;"></h4></div>'
//                } else {
//                  divStr += '<div style="position:absolute;z-index: 99;font-size:12px;text-align:center;top: 50%;left: 50%;-webkit-transform: translate(-50%, -50%);-moz-transform: translate(-50%, -50%);-ms-transform: translate(-50%, -50%);-o-transform: translate(-50%, -50%);transform: translate(-50%, -50%);"><h4 style="color: #3d82e5;border: 1px solid;border-radius: 20px;width: 22px;height: 22px;"></h4></div>'
//                }
              }
            }
          }
          return divStr
        } : () => ''
      },
      dayFn () {
        // 绘制今日日期时间
        // 将今日日期格式做修改达到 签到按钮能比对的数据结构 年-02-01（月份1-9前面加0）（日期前加0）
        let myDate = new Date()
        this.userData.dayDate = myDate.getFullYear() + '年' + parseInt(myDate.getMonth() + 1) + '月' + myDate.getDate() + '日'
        let month = parseInt(myDate.getMonth() + 1)
        if (month < 10) {
          month = '0' + parseInt(myDate.getMonth() + 1)
        }
        let myDay = parseInt(myDate.getDate())
        if (myDay < 10) {
          myDay = '0' + parseInt(myDate.getDate())
        }
        this.dayNum = myDate.getFullYear() + '-' + month + '-' + myDay
      },
      onShow () {
        // 弹窗出现时触发
      },
      onHide () {
        // 弹窗关闭时触发
      },
      moneyFn () {
        this.$router.push({
          path: '/pionts/IntegralCash'
        })
        this.$router.go(1)
      }
    }
  }
</script>
<style scoped="scoped">
  #userImg{
    width: 75px;
    border-radius: 50%;
  }
  .vux-prev-icon, .vux-next-icon{
    border: 1px solid #3d82e5!important;
  }
</style>
